package com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.hcpms.assessment.biz.service.AssessmentIndicatorService;
import com.paic.mhis.hcpms.assessment.biz.service.ExportWordService;
import com.paic.mhis.hcpms.assessment.common.AssessmentConstants;
import com.paic.mhis.hcpms.assessment.common.AssessmentSqlMapIdConstants;
import com.paic.mhis.hcpms.assessment.dto.EvaluateBatchDTO;
import com.paic.mhis.hcpms.assessment.dto.IndicaotrSourceDTO;
import com.paic.mhis.hcpms.assessment.dto.IndicatorConfigInfoDTO;
import com.paic.mhis.hcpms.assessment.dto.IndicatorDetailDTO;
import com.paic.mhis.hcpms.assessment.intergration.sao.FwaKpiSao;
import com.paic.mhis.hcpms.quota.calculationreport.calculationjob.biz.service.ComprehensiveEvaluationJobService;
import com.paic.mhis.hcpms.quota.calculationreport.kpiinterface.biz.service.KpiCoreDataService;
import com.paic.mhis.hcpms.quota.calculationreport.kpiinterface.dto.KpiConditionDTO;
import com.paic.mhis.hcpms.quota.calculationreport.kpiinterface.dto.KpiMedicalOrgDTO;

/**
 * 
 * Description:医院综合评价计算得分job
 * 
 * @author: EX-YUFEI002
 * @version:
 */
@Component("comprehensiveEvaluationJobService")
public class ComprehensiveEvaluationImpl implements ComprehensiveEvaluationJobService {

	private static final Log LOG = LogFactory.getLog(ComprehensiveEvaluationImpl.class);

	private static final String UNDERLINE = "_";

	private static final DecimalFormat DF = new DecimalFormat("0.0000");

	private static String[] gradeArr = { "2", "3", "4" };

	private String structureNo = "";

	@Resource
	private FwaKpiSao fwaKpiSao;

	@Autowired
	private CommonDAO commonDAO;

	@Autowired
	private KpiCoreDataService kpiCoreDataService;

	@Autowired
	private AssessmentIndicatorService assessmentIndicatorService;

	@Autowired
	private ExportWordService exportWordService;

	/**
	 * 统筹区+等级对应的指标项集合
	 */
	private Map<String, List<IndicatorDetailDTO>> structureInfoMap = new TreeMap<String, List<IndicatorDetailDTO>>();

	/**
	 * 
	 */
	private Map<String, IndicatorConfigInfoDTO> indicatorConfigMap = new TreeMap<String, IndicatorConfigInfoDTO>();

	@Override
	public void processComprehensiveEvaluation() {
		try {
			LOG.info("-----综合评价得分计算job进入-----");

			LOG.info("-----同步kpi批次信息并获取要计算批次-----");
			List<EvaluateBatchDTO> batchList = syncKpiBatchToCeBatch();

			if (CollectionUtils.isEmpty(batchList)) {
				LOG.info("job执行结束，没有需要计算的批次");
				return;
			}

			// 修改批次状态为计算中
			updateBatchStatus(batchList, AssessmentConstants.BATCH_STATUS_01);

			for (EvaluateBatchDTO batch : batchList) {
				try {
					List<Map<String, Object>> scoreList = new ArrayList<Map<String, Object>>();
					for (String grade : gradeArr) {
						// 根据regionCode和grade获取指标集合
						List<IndicatorDetailDTO> indicators = getIndicators(batch.getRegionCode(), grade);

						// 计算指标得分+
						scoreList.addAll(evaluateGradeBatch(batch, grade, indicators));
					}

					saveIndicatorScore(scoreList, batch);
				} catch (Exception e) {
					LOG.error(e, e);
					// 修改批次状态为计算失败
					updateBatchStatus(batch.getBatchNo(), AssessmentConstants.BATCH_STATUS_20);
				}

			}

			LOG.info("-----综合评价得分计算job结束-----");
		} catch (Exception e) {
			LOG.error(e, e);
		}
	}

	private List<Map<String, Object>> evaluateGradeBatch(EvaluateBatchDTO batch, String grade,
			List<IndicatorDetailDTO> levelIndicators) throws Exception {
		String kpiTime = batch.getKpiTime();
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (IndicatorDetailDTO indicatorDetail : levelIndicators) {
			if (StringUtils.equals(indicatorDetail.getSourceType(), AssessmentConstants.SOURCE_TYPE1)) {
				IndicatorConfigInfoDTO indicatorConfigInfo = getIndicatorConfig(indicatorDetail.getIndicatorCode(),
						grade, batch.getRegionCode());
				String startTime = kpiTime;
				if (indicatorConfigInfo.getTimeRange() != null) {
					startTime = getStartKpiTime(kpiTime, Integer.parseInt(indicatorConfigInfo.getTimeRange()));
				}

				KpiConditionDTO kpiConditionDTO = new KpiConditionDTO();
				kpiConditionDTO.setSociationCode(batch.getRegionCode());
				kpiConditionDTO.setPeriod(batch.getPeriod());
				kpiConditionDTO.setKpiTime(kpiTime);
				kpiConditionDTO.setKpiCode(indicatorDetail.getKpiCode());
				kpiConditionDTO.setVisitType(indicatorDetail.getVisitType());
				kpiConditionDTO.setGrade(grade);
				List<IndicaotrSourceDTO> target = getIndicaotrSourceList(kpiConditionDTO,
						indicatorDetail.getValueType(), indicatorDetail.getIndicatorCode(),
						indicatorDetail.getFullMark());

				if (CollectionUtils.isEmpty(target)) {
					continue;
				}
				System.out.println("target=" + target.size());

				// 设置样本范围
				kpiConditionDTO.setKpiTime(null);
				kpiConditionDTO.setKpiTimeEnd(kpiTime);
				kpiConditionDTO.setKpiTimeStart(startTime);
				// 如果是全部比较，设置查询的等级为空
				if (StringUtils.equals(indicatorConfigInfo.getCompareRange(), AssessmentConstants.COMPARERANGE_TYPE1)) {
					kpiConditionDTO.setGrade(null);
				}
				// 如果是二级及以上
				else if (StringUtils.equals(indicatorConfigInfo.getCompareRange(),
						AssessmentConstants.COMPARERANGE_TYPE4)) {
					kpiConditionDTO.setGrade(null);
					List<String> gradeList = new ArrayList<String>();
					gradeList.add(AssessmentConstants.HOSPITAL_LEVEL2);
					gradeList.add(AssessmentConstants.HOSPITAL_LEVEL3);
					kpiConditionDTO.setGradeList(gradeList);
				}
				List<IndicaotrSourceDTO> sample = getIndicaotrSourceList(kpiConditionDTO,
						indicatorDetail.getValueType(), indicatorDetail.getIndicatorCode(),
						indicatorDetail.getFullMark());

				System.out.println("sample=" + sample.size());

				LOG.info("important 开始计算指标" + indicatorDetail.getIndicatorCode() + "医院等级" + kpiConditionDTO.getGrade()
						+ " kpi:" + indicatorDetail.getKpiCode() + " 对比范围：" + indicatorConfigInfo.getTimeRange()
						+ "  startTime:" + kpiConditionDTO.getKpiTimeStart() + " endTime:"
						+ kpiConditionDTO.getKpiTimeEnd() + " 样本数量：" + target.size());
				try {
					List<IndicaotrSourceDTO> indicatorScoreList = assessmentIndicatorService.getIndicatorScore(sample,
							target, indicatorDetail.getIndicatorCode(), grade, batch.getRegionCode(),
							batch.getKpiTime());
					resultList.addAll(createResult(indicatorScoreList));
				} catch (Exception e) {
					LOG.error(e, e);
					LOG.info("计算指标" + indicatorDetail.getIndicatorCode() + "得分异常");
				}

			}
		}

		return resultList;

	}

	public void saveIndicatorScore(List<Map<String, Object>> resultList, EvaluateBatchDTO evaluateBatch)
			throws Exception {
		if (!CollectionUtils.isEmpty(resultList)) {

			// 删除批次下老数据hcpms_ce_score
			commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_DEL_BATCH_SCORE, evaluateBatch);

			// 删除批次下老数据hcpms_ce_data
			commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_DEL_BATCH_DATA, evaluateBatch);

			// 插入批次本次计算指标得分（hcpms_ce_score）
			commonDAO.insertBatch(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_SCORE, resultList);

			// 插入批次本次计算kpi得分（hcpms_ce_data）
			commonDAO.insertBatch(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_DATA, resultList);
			Map<String, Object> paramsMap1 = new HashMap<String, Object>();
			paramsMap1.put("regioncode", evaluateBatch.getRegionCode());
			paramsMap1.put("grade", "");
			paramsMap1.put("kpiTime", evaluateBatch.getKpiTime());
			paramsMap1.put("period", evaluateBatch.getPeriod());
			paramsMap1.put("structureNo", structureNo);

			// 在data中有记录的医院编码
			List<String> hasResultList = commonDAO.query(AssessmentSqlMapIdConstants.ASSESSMENT_QUERY_PROVIDERS,
					paramsMap1);

			// 同步来源类型是接口的kpi数据
			for (String providerCode : hasResultList) {
				try {
					LOG.info("同步来源类型是接口的kpi数据regionCode=" + evaluateBatch.getRegionCode() + "providerCode="
							+ providerCode + "KpiTime" + evaluateBatch.getKpiTime());
					fwaKpiSao.invokeMedicalOrgInfoESA(evaluateBatch.getRegionCode(), providerCode,
							evaluateBatch.getKpiTime());
				} catch (Exception e) {
					LOG.info("------同步来源类型是接口的kpi数据的数据失败-------");
					LOG.error(e, e);
				}

			}

			try {
				for (String grade : gradeArr) {
					// 根据regionCode和grade获取指标集合
					List<IndicatorDetailDTO> indicators = getIndicators(evaluateBatch.getRegionCode(), grade);
					List<Map<String, Object>> fwaScores = evaluateFwaIndicator(evaluateBatch, grade, indicators);
					// 插入批次本次计算指标得分（hcpms_ce_score）
					commonDAO.insertBatch(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_SCORE, fwaScores);
				}
			} catch (Exception e) {
				LOG.info("------fwa指标计算失败-------");
				LOG.error(e, e);
			}

			// 刷医院1、2级指标得分
			for (String providerCode : hasResultList) {
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				paramsMap.put("providerCode", providerCode);
				paramsMap.put("period", evaluateBatch.getPeriod());
				paramsMap.put("kpiTime", evaluateBatch.getKpiTime());
				paramsMap.put("regionCode", evaluateBatch.getRegionCode());
				paramsMap.put("structureNo", structureNo);

				paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL2);
				commonDAO.insert(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE, paramsMap);

				paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL1);
				commonDAO.insert(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE, paramsMap);

				paramsMap.put("level", AssessmentConstants.INDICATOR_LEVEL0);
				commonDAO.insert(AssessmentSqlMapIdConstants.ASSESSMENT_INSERT_PARENT_SCORE, paramsMap);
			}

			// 刷新指标得分百分比
			commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_UPDATE_PERCENT_SCORE, paramsMap1);

			// 该批次计算成功
			updateBatchStatus(evaluateBatch.getBatchNo(), AssessmentConstants.BATCH_STATUS_02);
			LOG.info("-----成功插入" + resultList.size() + "条记录-----");
		} else {
			updateBatchStatus(evaluateBatch.getBatchNo(), AssessmentConstants.BATCH_STATUS_00);
			LOG.info("-----没有插入数据，计算失败-----");
		}
	}

	private List<Map<String, Object>> evaluateFwaIndicator(EvaluateBatchDTO batch, String grade,
			List<IndicatorDetailDTO> levelIndicators) throws Exception {
		String kpiTime = batch.getKpiTime();
		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
		for (IndicatorDetailDTO indicatorDetail : levelIndicators) {
			if (StringUtils.equals(indicatorDetail.getSourceType(), AssessmentConstants.SOURCE_TYPE3)) {
				IndicatorConfigInfoDTO indicatorConfigInfo = getIndicatorConfig(indicatorDetail.getIndicatorCode(),
						grade, batch.getRegionCode());
				String startTime = kpiTime;
				if (indicatorConfigInfo.getTimeRange() != null) {
					startTime = getStartKpiTime(kpiTime, Integer.parseInt(indicatorConfigInfo.getTimeRange()));
				}

				KpiConditionDTO kpiConditionDTO = new KpiConditionDTO();
				kpiConditionDTO.setSociationCode(batch.getRegionCode());
				kpiConditionDTO.setPeriod(batch.getPeriod());
				kpiConditionDTO.setKpiTime(kpiTime);
				kpiConditionDTO.setKpiCode(indicatorDetail.getIndicatorCode());
				kpiConditionDTO.setVisitType(indicatorDetail.getVisitType());
				kpiConditionDTO.setGrade(grade);

				// 目标数据
				List<IndicaotrSourceDTO> target = getFwaIndicaotrSourceList(kpiConditionDTO,
						indicatorDetail.getValueType(), indicatorDetail.getIndicatorCode(),
						indicatorDetail.getFullMark(), false);

				if (CollectionUtils.isEmpty(target)) {
					continue;
				}
				LOG.info("fwatarget=" + target.size());

				// 设置样本范围
				kpiConditionDTO.setKpiTime(null);
				kpiConditionDTO.setKpiTimeEnd(kpiTime);
				kpiConditionDTO.setKpiTimeStart(startTime);
				// 如果是全部比较，设置查询的等级为空
				if (StringUtils.equals(indicatorConfigInfo.getCompareRange(), AssessmentConstants.COMPARERANGE_TYPE1)) {
					kpiConditionDTO.setGrade(null);
				}

				// 样本数据
				List<IndicaotrSourceDTO> sample = getFwaIndicaotrSourceList(kpiConditionDTO,
						indicatorDetail.getValueType(), indicatorDetail.getIndicatorCode(),
						indicatorDetail.getFullMark(), true);

				LOG.info("fwasample=" + sample.size());

				List<IndicaotrSourceDTO> indicatorScoreList = assessmentIndicatorService.getIndicatorScore(sample,
						target, indicatorDetail.getIndicatorCode(), grade, batch.getRegionCode(), batch.getKpiTime());
				resultList.addAll(createResult(indicatorScoreList));
			}
		}

		return resultList;

	}

	/**
	 * 封装保存对象
	 * 
	 * @param indicatorScoreList
	 * @return
	 * @throws Exception
	 */
	private List<Map<String, Object>> createResult(List<IndicaotrSourceDTO> indicatorScoreList) throws Exception {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (IndicaotrSourceDTO dto : indicatorScoreList) {
			if (dto.getIndicatorScore() == null) {
				continue;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ID_INDICATOR", dto.getIndicator_code());
			map.put("HEALTHCARE_PROVIDER_CODE", dto.getProvider_code());
			map.put("PERIOD", dto.getPeriod());
			map.put("KPI_TIME", dto.getKpi_time());
			map.put("STRUCTURE_DATA", dto);
			map.put("REGION_CODE", dto.getRegion_code());
			map.put("PERCENT_SCORE", dto.getIndicatorScore().getScore());
			map.put("STRUCTURE_SCORE", dto.getIndicatorScore().getScore() / 100.0 * getDouble(dto.getIndicatorWeight()));
			map.put("STRUCTURE_DATA", dto.getIndicator_value());
			map.put("LOWER_LIMIT", dto.getIndicatorScore().getLower_limit());
			map.put("UPPER_LIMIT", dto.getIndicatorScore().getUpper_limit());
			map.put("IS_VALID", 0);
			list.add(map);
		}

		return list;
	}

	/**
	 * 获取指标信息
	 * 
	 * @param regionCode
	 * @param grade
	 * @return
	 * @throws Exception
	 */
	private List<IndicatorDetailDTO> getIndicators(String regionCode, String grade) throws Exception {
		List<IndicatorDetailDTO> list = new ArrayList<IndicatorDetailDTO>();
		String key = regionCode + "_" + grade;
		if (structureInfoMap.containsKey(key)) {
			list = structureInfoMap.get(key);
		} else {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("regioncode", regionCode);
			params.put("grade", grade);
			structureNo = exportWordService.getStructureNo(params);
			list = commonDAO.query(AssessmentSqlMapIdConstants.ASSESSMENT_QUERY_INDICATORS, structureNo);
			structureInfoMap.put(key, list);
		}

		return list;
	}

	/**
	 * 获取指标配置信息
	 * 
	 * @param indicatorCode
	 * @param grade
	 * @param regionCode
	 * @return
	 * @throws Exception
	 */
	private IndicatorConfigInfoDTO getIndicatorConfig(String indicatorCode, String grade, String regionCode)
			throws Exception {
		IndicatorConfigInfoDTO indicatorConfigInfo = null;
		String key = indicatorCode + "_" + grade + "_" + regionCode;
		if (indicatorConfigMap.containsKey(key)) {
			indicatorConfigInfo = indicatorConfigMap.get(key);
		} else {
			indicatorConfigInfo = assessmentIndicatorService.getIndicatorConfig(indicatorCode, regionCode, grade);
			indicatorConfigMap.put(key, indicatorConfigInfo);
		}

		return indicatorConfigInfo;
	}

	/**
	 * 
	 * Description:
	 * 
	 * @return
	 * 
	 *         Modification History: Date Version Author Description
	 *         ------------
	 *         ------------------------------------------------------ 2015-3-11
	 *         mhis_hcpms EX-ZENGYUANCHAO001 创建
	 */
	public List<EvaluateBatchDTO> syncKpiBatchToCeBatch() {
		commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_SYNC_BATCH, null);
		return commonDAO.query("evaluate.getBatchs", null);
	}

	/**
	 * 查询kpi数据
	 * 
	 * @param condition
	 * @param valueType
	 * @param indicatorCode
	 * @param fullMark
	 * @return
	 * @throws Exception
	 */
	private List<IndicaotrSourceDTO> getIndicaotrSourceList(KpiConditionDTO condition, String valueType,
			String indicatorCode, BigDecimal fullMark) throws Exception {
		List<IndicaotrSourceDTO> indicaotrSourceList = new ArrayList<IndicaotrSourceDTO>();
		try {

			List<KpiMedicalOrgDTO> list = kpiCoreDataService.queryKpiByOrg(condition);
			for (KpiMedicalOrgDTO kpiOrg : list) {
				IndicaotrSourceDTO indicaotrSource = new IndicaotrSourceDTO();
				indicaotrSource.setIndicator_code(indicatorCode);
				indicaotrSource.setKpi_time(condition.getKpiTime());
				indicaotrSource.setPeriod(condition.getPeriod());
				indicaotrSource.setProvider_code(kpiOrg.getMedicalOrgCode());
				indicaotrSource.setProvider_level(condition.getGrade());
				indicaotrSource.setRegion_code(condition.getSociationCode());
				indicaotrSource.setIndicatorWeight(fullMark);
				if (StringUtils.equals("0", valueType)) {
					indicaotrSource.setIndicator_value(getDouble(kpiOrg.getKpiValue()));
				} else if (StringUtils.equals("1", valueType)) {
					indicaotrSource.setIndicator_value(getDouble(kpiOrg.getPeriodRatio()));
				} else if (StringUtils.equals("2", valueType)) {
					indicaotrSource.setIndicator_value(getDouble(kpiOrg.getChainRatio()));
				}
				indicaotrSourceList.add(indicaotrSource);
			}

		} catch (Exception e) {
			LOG.error(e, e);
		}
		return indicaotrSourceList;
	}

	/**
	 * 查询kpi数据
	 * 
	 * @param condition
	 * @param valueType
	 * @param indicatorCode
	 * @param fullMark
	 * @return
	 * @throws Exception
	 */
	private List<IndicaotrSourceDTO> getFwaIndicaotrSourceList(KpiConditionDTO condition, String valueType,
			String indicatorCode, BigDecimal fullMark, boolean getAll) throws Exception {
		List<IndicaotrSourceDTO> indicaotrSourceList = new ArrayList<IndicaotrSourceDTO>();
		try {

			String sqlMap = AssessmentSqlMapIdConstants.ASSESSMENT_GET_INT_SCORE;
			if (getAll) {
				sqlMap = AssessmentSqlMapIdConstants.ASSESSMENT_GET_INT_SCORES;
			}

			List<Map<String, Object>> list = commonDAO.query(sqlMap, condition);
			for (Map<String, Object> fwaData : list) {
				IndicaotrSourceDTO indicaotrSource = new IndicaotrSourceDTO();
				indicaotrSource.setIndicator_code(indicatorCode);
				indicaotrSource.setKpi_time(fwaData.get("KPITIME").toString());
				indicaotrSource.setPeriod(condition.getPeriod());
				indicaotrSource.setProvider_code(fwaData.get("PROVIDERCODE").toString());
				indicaotrSource.setProvider_level(condition.getGrade());
				indicaotrSource.setRegion_code(condition.getSociationCode());
				indicaotrSource.setIndicatorWeight(fullMark);
				indicaotrSource.setIndicator_value(getDouble(new BigDecimal(fwaData.get("KPIVALUE").toString())));
				indicaotrSourceList.add(indicaotrSource);
			}

		} catch (Exception e) {
			LOG.error(e, e);
		}
		return indicaotrSourceList;
	}

	private Double getDouble(BigDecimal kpiValue) {
		if (kpiValue == null) {
			return 0.0;
		}
		return Double.parseDouble(DF.format(kpiValue));
	}

	/**
	 * 刷新多个批次状态
	 */
	private void updateBatchStatus(List<EvaluateBatchDTO> batchList, String status) throws Exception {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			for (EvaluateBatchDTO batch : batchList) {
				params.put("batchNo", batch.getBatchNo());
				params.put("status", status);
				commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_UPDATE_BATCH_STATUS, params);
			}
		} catch (Exception e) {
			LOG.error(e, e);
		}
	}

	/**
	 * 刷新单个批次状态
	 */
	private void updateBatchStatus(String batchNo, String status) throws Exception {
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("batchNo", batchNo);
			params.put("status", status);
			commonDAO.update(AssessmentSqlMapIdConstants.ASSESSMENT_UPDATE_BATCH_STATUS, params);

		} catch (Exception e) {
			LOG.error(e, e);
		}
	}

	/**
	 * 获取当前时间过去月份 Description:
	 * 
	 * @param emdTime
	 * @param time
	 * @return
	 * @throws ParseException
	 * 
	 *             Modification History: Date Version Author Description
	 *             --------
	 *             ----------------------------------------------------------
	 *             2015-3-18 mhis_hcpms EX-YUFEI002 创建
	 */
	private String getStartKpiTime(String endTime, int time) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
		String dateString = null;
		Date date = null;
		try {
			date = format.parse(endTime);
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.MONTH, -(time - 1));
			dateString = format.format(calendar.getTime());
		} catch (Exception e) {
			LOG.error(e, e);
		}

		return dateString;
	}

}
